<template>
  <div>
      <input type="file" class="file" ref="file" @change="uploadAvatar" >
      <img :src="pic" alt="" class="avatar" @click="handleClick">
  </div>
</template>

<script>
import {uploadpic} from "@/api";
import {axios,baseURL} from "@/utils/axios"
export default {
    props:["userinfo"],
    data(){
        return{
            pic:require("@/assets/images/touxiang.jpg")
        }
    },
    methods:{
        handleClick(){
            this.$refs.file.click();
        },
        uploadAvatar(){
            // console.log("开始上传");
            var file = this.$refs.file.files[0]

            // 创建表单对象  
            var data = new FormData();
            data.append("avatar",file);

            uploadpic(data)
           .then(res=>{
            //    if(res.type){
            //        this.pic = res.avatar.replace(/public/,baseURL);  // 图片地址优化
            //    }
           })
        }
    },
     mounted(){
        // 判断是否此用户是否有上传过头像
        if(this.userinfo){
            if(this.userinfo.avatar){
                this.pic = this.userinfo.avatar.replace(/public/,baseURL)
            }else{
                this.pic = require("@/assets/images/touxiang.jpg")
            }
        }else{
            this.pic = require("@/assets/images/touxiang.jpg")
        }
    },
}
</script>

<style lang="scss" scoped>
.avatar{
    width: 45px;
    height: 45px;
    border-radius: 50%;
    cursor: pointer;
}
.file{
    display: none;
}
</style>